package api

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"github.com/spf13/cast"
	"net/http"
	"zsc-boot/app/message/service"
	service2 "zsc-boot/app/system_layer/service"
	"zsc-boot/core/web"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func WebWs(c *gin.Context) {
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		web.FailResponse(c, err, "建立websocket连接失败")
		return
	}

	//获取用户信息
	userIdStr := c.Request.URL.Query().Get("userId")
	userId := cast.ToInt(userIdStr)
	if userId == 0 {
		web.FailResponse(c, nil, "请先登录")
		return
	}
	//上线
	service.UserOnline(userId, conn, service.Web)

	if service.GetUserConn(userId, service.App) == nil {
		//_ = service.SendUserMsg(userId, "app端离线", service.Web, "offline")
	} else {
		//_ = service.SendUserMsg(userId, "web端已上线", service.App, "online")
		//_ = service.SendUserMsg(userId, "app端在线", service.Web, "online")
	}

	for {
		_, _, msgErr := conn.ReadMessage()
		if msgErr != nil {
			//离线
			service.UserOffline(userId, service.Web)
			//_ = service.SendUserMsg(userId, "web端已离线", service.App, "offline")
			break
		}
	}
}

func AppWs(c *gin.Context) {
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		web.FailResponse(c, err, "建立websocket连接失败")
		return
	}

	//获取用户信息
	userId := service2.GetUserID(c)
	if userId == 0 {
		web.FailResponse(c, nil, "请先登录")
		return
	}

	//上线
	service.UserOnline(userId, conn, service.App)

	if service.GetUserConn(userId, service.Web) == nil {
		//_ = service.SendUserMsg(userId, "web端离线", service.App, "offline")
	} else {
		//_ = service.SendUserMsg(userId, "app端已上线", service.Web, "online")
		//_ = service.SendUserMsg(userId, "web端在线", service.App, "online")
	}

	for {
		_, _, msgErr := conn.ReadMessage()
		if msgErr != nil {
			//离线
			service.UserOffline(userId, service.App)
			//_ = service.SendUserMsg(userId, "app端已离线", service.Web, "offline")
			break
		}
	}
}
